package com.pocketsweet.ui;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Timer;

import org.json.JSONException;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.PushService;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.easemob.EMCallBack;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMChatOptions;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMMessage.ChatType;
import com.easemob.chat.EMNotifier;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.easemob.util.NetUtils;
import com.pocketsweet.C;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLCache;
import com.pocketsweet.MLContext;
import com.pocketsweet.MLOrderTimer;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.chat.ui.activity.ChatActivity;
import com.pocketsweet.chat.ui.activity.ChatAllHistoryFragment;
import com.pocketsweet.chat.ui.activity.RandomCallActivity;
import com.pocketsweet.chatlib.controller.HXSDKHelper;
import com.pocketsweet.chatlib.controller.MolianContactManager;
import com.pocketsweet.chatlib.controller.MolianContactManager.MolianContactListerner;
import com.pocketsweet.chatui.Constant;
import com.pocketsweet.chatui.db.InviteMessgeDao;
import com.pocketsweet.chatui.domain.User;
import com.pocketsweet.dao.SystemConfigManager;
import com.pocketsweet.model.MLCustomizationRecord;
import com.pocketsweet.model.MLException;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.model.MLVoice;
import com.pocketsweet.service.UpdateService;
import com.pocketsweet.service.UserService;
import com.pocketsweet.service.shareService;
import com.pocketsweet.ui.fragments.ExploreFragment;
import com.pocketsweet.ui.fragments.FriendFragment;
import com.pocketsweet.ui.fragments.HomeFragment;
import com.pocketsweet.ui.fragments.NewOnlineFragment;
import com.pocketsweet.ui.fragments.RecommendFragment;
import com.pocketsweet.ui.fragments.SelfFragment;
import com.pocketsweet.ui.uilib.FragmentTabHost;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.MyOnTouchListener;
import com.pocketsweet.ui.uilib.coutdownView;
import com.pocketsweet.ui.uilib.coutdownView.OnTimeCompleteListener;
import com.pocketsweet.utils.ShareReferanceUtils;
import com.pocketsweet.utils.ToolKits;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.umeng.update.UpdateConfig;

public class Main extends BaseActivity implements TencentLocationListener,
        OnClickListener, OnTouchListener {
    /*
     * 聊天相关信息
     */
    protected static final String TAG = "MainActivity";

    // 未读消息textview
    private TextView unreadLabel;
    // 未读订单
    private ImageView unreadCustomazitionLable;
    // 未读编辑推荐textview
    private ImageView unread_recommend;
    // 账号在别处登录
    public boolean isConflict = false;
    // 账号被移除
    private boolean isCurrentAccountRemoved = false;
    private NewMessageBroadcastReceiver msgReceiver;

    private InviteMessgeDao inviteMessgeDao;

    private android.app.AlertDialog.Builder conflictBuilder;
    private android.app.AlertDialog.Builder accountRemovedBuilder;
    private boolean isConflictDialogShow;
    private boolean isAccountRemovedDialogShow;

    public boolean msgFragmentisShow = false;
    public boolean friendFragmentisShow = false;
    public boolean selfFragmentisShow = false;

    // 定制相关
    public static String customazitonLoverId = null;
    public static RelativeLayout rlLoverInvited;
    public static RelativeLayout rlNightWhisper;
    private TextView btnOk;

    private TextView imgCall;

    private LinearLayout linOk;

    private ImageView tvClose;

    private TextView tv_tips;
    private TextView btnKnow;

    private coutdownView countdownTimer;

    private int countdownTime = 600;// 倒计时时间
    MLCustomizationRecord mlCustomizationRecord;
    public static boolean isConnect = false;
    public static boolean isBalanceChange = false;// 是否充值
    public static MLCustomizationRecord record;
    // 双击
    private int count = 0;
    private int firClick = 0;
    private int secClick = 0;
    /*
     * 其他页面信息
     */
    private static Main _instance;
    private shareService myShareSevice;// 友盟分享service
    private Fragment mContent;
    private long mExitTime = 0;// 退出事件用到的事件

    public static final String ACTION_CHAT_RECEIVE_MESSAGE = "action_chat_receive_message";
    public static final String ACTION_CHOOSE_CHANGE = "action_choose_change";
    public static final String ACTION_COMMENT_COMMIT = "action_comment_commit";
    public static final String ACTION_LIKE_POEPLE = "action_like_people";
    public static final String ACTION_NEW_INVITED = "action_new_invited";
    public static final String ACTION_LIKE_POEPLE_REFRESH = "action_like_people_refresh";
    public static final String ACTION_LIKE_RECOMMEND = "action_like_recommend";
    public static final String ACTION_LIKE_RECOMMEND_REFRESH = "action_like_recommend_refresh";
    public static final String ACTION_LIKE_TAB = "action_like_tab";
    public static final String ACTION_VOICE = "action_voice";
    public static final String ACTION_ADDFRIEND_SUCCESS = "action_addfriend_success";
    public static final String MESSAGE_ACCEPT = "message_accept";
    public static final String MESSAGE_VOICE = "message_voice";
    public static final String MESSAGE_SHAKE = "message_shake";
    public static final String MESSAGE_BORDER = "message_border";

    public FragmentTransaction mFragmentTransaction;
    public FragmentManager fragmentManager;
    public static int currentTabIndex = 0;
    private int index;
    private Button[] mTabs;
    // 定义FragmentTabHost对象
    private FragmentTabHost mTabHost;

    // 定义一个布局
    private LayoutInflater layoutInflater;

    private HomeFragment mHomeFragment;
    private ChatAllHistoryFragment mChatAllHistoryFragment;
    private ExploreFragment mExploreFragment;
    private SelfFragment mSelfFragment;
    private Fragment[] fragments;

    // 腾讯定位
    private static final long[] INTERVALS = new long[]{2 * 1000, 3 * 1000,
            5 * 1000, 10 * 1000};
    private static final int DEFAULT = 2;
    private int mIndex = DEFAULT;
    private long mInterval = INTERVALS[DEFAULT];
    private TencentLocationManager mLocationManager;
    public static double mLontitude;
    public static double mLatitude;
    public static String locatedCity;

    // 自动更新监测
    private UpdateService myUpdateService;
    private HeaderLayout rvHeader;

    public static int choosedSex = 0;// 0为全部；1为男；2为女
    public static int choosedCity = 0;// 0为全部；1为同城
    public static int choosedType = 0;// 0为全部：1为只查看推荐的
    public static boolean needRefresh = false;// 告知列表页面是否需要刷新
    public static final int REQUEST_CODE_CHOOSE = 0x01;

    // 声线
    public static AVFile audioFile;
    public static String curPlayId = "";// 当前播放的id
    public static String playId = "";// 要播放的Id
    public static int playItem;// 要播放的Id
    public static int curPlayItem;// 当前播放地item
    public static MediaPlayer mMediaPlayer;
    public static Timer MediaTimer;
    public static ArrayList<MLVoice> voiceList = new ArrayList<MLVoice>();

    // 自定义的广播接收
    public BroadcastReceiver MainReciver;

    // 消息是否勿扰
    private EMChatOptions chatOptions;
    private BroadcastReceiver borderReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Main.MESSAGE_BORDER)) {
                // Log.e("==isBorder", "isBorder again");
                isBorder();
            }
        }
    };


    public static Main getInstance() {
        return _instance;
    }

    /**
     * 检查当前用户是否被删除
     */
    public boolean getCurrentAccountRemoved() {
        return isCurrentAccountRemoved;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        _instance = this;
        setContentView(R.layout.activity_main);

        // overridePendingTransition(R.anim.fade_in, R.anim.unzoom_out);
        if (savedInstanceState != null
                && savedInstanceState.getBoolean(Constant.ACCOUNT_REMOVED,
                false)) {
            // 防止被移除后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            MLApplication.getInstance().logout(null);
            finish();
            startActivity(new Intent(this, TempMain.class));
            return;
        } else if (savedInstanceState != null
                && savedInstanceState.getBoolean("isConflict", false)) {
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            finish();
            startActivity(new Intent(this, TempMain.class));
            return;
        }

        // if (UserService.getCurrentUser() == null) {
        // startActivity(new Intent(this, Login.class));
        // }
        if (UserService.getCurrentUser() != null) {
            if (UserService.getCurrentUser().getGender() == 1) {
                choosedSex = 2;
            } else if (UserService.getCurrentUser().getGender() == 2) {
                choosedSex = 1;
            }
        }
        initView();
        sendWelcom();
        initTestOrder();
        setLocalImage();
        // 初始化一些组件，包括欢迎页面，版本更新检查和社会化分享，高德定位
        initComponents();

        initIm();
        initMyReceiver();
        isBorder();
        initCallInvited();
        MLOrderTimer.getAllOrderTimer();
        // 检测异常记录
        checkException();

    }

    @SuppressWarnings("static-access")
    private void checkException() {
        if (MLApplication.getInstance().getIsLogin() == false || UserService.getCurrentUser() == null) {
            return;
        }
        if (MLContext.getInstance().getExceotionUserMoney() == 0) {
            MLContext.getInstance().saveExceotionUserMoney(
                    (int) UserService.getCurrentUser().getBalance());
        } else {
            if (MLApplication.getInstance().getIsLogin() == false) {
                return;
            }
            int sum = (int) (UserService.getCurrentUser().getBalance() - MLContext
                    .getInstance().getExceotionUserMoney());
            if (sum > 30) {
                // 账号异常金额
                MLException exception = new MLException();
                exception.setUser(UserService.getCurrentUser());
                exception.setSum(sum);
                exception.saveInBackground();
            }
        }
    }

    private void initCallInvited() {
        isConnect = true;
        if (UserService.getCurrentUser() == null) {
            return;
        }
        if (UserService.getCurrentUser().getBalance() >= 2) {
            btnOk.setText("确定");
            btnOk.setVisibility(View.VISIBLE);
            btnOk.setTextColor(getResources().getColor(R.color.white));
            linOk.setBackgroundResource(R.drawable.shape_btn_login);
            linOk.setClickable(true);
            imgCall.setVisibility(View.GONE);
            countdownTimer.setVisibility(View.GONE);
            linOk.setOnClickListener(this);
        } else {
            btnOk.setText("余额不足");
            btnOk.setTextColor(getResources().getColor(
                    R.color.main_text_color_pink));
            linOk.setBackgroundResource(R.drawable.shape_btn_sure_grey);
            linOk.setClickable(false);
            imgCall.setVisibility(View.GONE);
            countdownTimer.setVisibility(View.GONE);

        }
        tvClose.setOnClickListener(this);
        tv_tips.setText(getResources().getString(R.string.loveCall_tips));

    }

    private void initTestOrder() {
        // 查询是否今天已经进行过试聊
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", UserService.getCurrentUserId());
        AVCloud.callFunctionInBackground("isHasTestOrder", params,
                new FunctionCallback<String>() {

                    @Override
                    public void done(String result, AVException e) {
                        if (e == null) {
                            if (result.equals("true")) {
                                MLContext.isTestOrderToday = true;
                            } else {
                                MLContext.isTestOrderToday = false;
                            }
                        } else {
                            ToolKits.toast(Main.this, "请检查网络");
                        }
                    }

                });

    }

    private void setLocalImage() {
        if (UserService.getCurrentUser() == null) {
            return;
        }
        // 兼容第一版本，如果是更新上来的，添加

        // if
        // (MLCache.getCache().getAsJSONObject(UserService.getCurrentUserId())
        // == null) {
        // MLCache.InitUser();
        // }

        if (UserService.getCurrentUser().getSubAvatar() == null
                || UserService.getCurrentUser().getSubAvatar().equals("")) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", UserService.getCurrentUserId());
            AVCloud.callFunctionInBackground("creatSubAvatar", params,
                    new FunctionCallback<Object>() {

                        @Override
                        public void done(Object o, AVException e) {
                            if (e == null) {
                                MLCache.getCache().put(
                                        UserService.getCurrentUserId(),
                                        UserService.getCurrentUser()
                                                .toJSONObject());
                            }
                        }
                    });
        }

    }

    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Main.MESSAGE_BORDER);
        registerReceiver(borderReceiver, filter);
    }

    // 是否勿扰时段
    private void isBorder() {
        chatOptions = EMChatManager.getInstance().getChatOptions();
        if (MLContext.getMessage("message_border")) {// 如果设置了勿扰时段
            if (isNight()) {// 是勿扰时段，屏蔽
                chatOptions.setNotificationEnable(false);
                chatOptions.setShowNotificationInBackgroud(false);
                EMChatManager.getInstance().setChatOptions(chatOptions);
                HXSDKHelper.getInstance().getModel()
                        .setSettingMsgNotification(false);
            } else {// 没设置勿扰时段
                chatOptions.setNotificationEnable(true);
                chatOptions.setShowNotificationInBackgroud(true);
                EMChatManager.getInstance().setChatOptions(chatOptions);
                HXSDKHelper.getInstance().getModel()
                        .setSettingMsgNotification(true);
            }
        } else {
            if (MLContext.getMessage(MESSAGE_ACCEPT)) {
                chatOptions.setNotificationEnable(true);
                EMChatManager.getInstance().setChatOptions(chatOptions);
                HXSDKHelper.getInstance().getModel()
                        .setSettingMsgNotification(true);
                if (MLContext.getMessage(MESSAGE_VOICE)) {
                    chatOptions.setNoticeBySound(true);
                    EMChatManager.getInstance().setChatOptions(chatOptions);
                    HXSDKHelper.getInstance().getModel()
                            .setSettingMsgSound(true);
                } else {
                    chatOptions.setNoticeBySound(false);
                    EMChatManager.getInstance().setChatOptions(chatOptions);
                    HXSDKHelper.getInstance().getModel()
                            .setSettingMsgSound(false);
                }
                if (MLContext.getMessage(MESSAGE_SHAKE)) {
                    chatOptions.setNoticedByVibrate(true);
                    EMChatManager.getInstance().setChatOptions(chatOptions);
                    HXSDKHelper.getInstance().getModel()
                            .setSettingMsgVibrate(true);
                } else {
                    chatOptions.setNoticedByVibrate(false);
                    EMChatManager.getInstance().setChatOptions(chatOptions);
                    HXSDKHelper.getInstance().getModel()
                            .setSettingMsgVibrate(false);
                }
            } else {
                chatOptions.setNotificationEnable(false);
                EMChatManager.getInstance().setChatOptions(chatOptions);
                HXSDKHelper.getInstance().getModel()
                        .setSettingMsgNotification(false);
            }
        }
    }

    // 发送欢迎消息
    private void sendWelcom() {
        if (SystemConfigManager.getInstance(Main.this).isFirstLogin()) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("touserId", UserService.getCurrentUserId());
            params.put("type", 1);
            AVCloud.callFunctionInBackground("sendSysMsg", params,
                    new FunctionCallback<Object>() {

                        @Override
                        public void done(Object arg0, AVException e) {
                            if (e == null) {
                                SystemConfigManager.getInstance(Main.this)
                                        .setFirstLogin(false);
                            }

                        }
                    });
        }

    }

    private void initMyReceiver() {
        MainReciver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                // 同意加对方为好友
                if (intent.getAction().equals(ACTION_ADDFRIEND_SUCCESS)) {
                    mChatAllHistoryFragment.refresh();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_ADDFRIEND_SUCCESS);
        registerReceiver(MainReciver, filter);
    }

    private void initIm() {
        if (getIntent().getBooleanExtra("conflict", false)
                && !isConflictDialogShow) {
            showConflictDialog();
        } else if (getIntent().getBooleanExtra(Constant.ACCOUNT_REMOVED, false)
                && !isAccountRemovedDialogShow) {
            showAccountRemovedDialog();
        }

        inviteMessgeDao = new InviteMessgeDao(this);
        // 这个fragment只显示好友和群组的聊天记录
        // chatHistoryFragment = new ChatHistoryFragment();
        // 注册一个接收消息的BroadcastReceiver
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager
                .getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        // 注册一个ack回执消息的BroadcastReceiver
        IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager
                .getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(3);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        // 注册一个透传消息的BroadcastReceiver
        IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager
                .getInstance().getCmdMessageBroadcastAction());
        cmdMessageIntentFilter.setPriority(3);
        registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);

        // //注册语音监听
        // IntentFilter callFilter = new
        // IntentFilter(EMChatManager.getInstance()
        // .getIncomingCallBroadcastAction());
        // registerReceiver(incomingReceiver, callFilter);
        // 注册一个离线消息的BroadcastReceiver
        // IntentFilter offlineMessageIntentFilter = new
        // IntentFilter(EMChatManager.getInstance()
        // .getOfflineMessageBroadcastAction());
        // registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);

        // setContactListener监听联系人的变化等
        MolianContactManager.getInstance().setContactListener(
                new MyContactListener());
        // 注册一个监听连接状态的listener
        EMChatManager.getInstance().addConnectionListener(
                new MyConnectionListener());
        // 注册群聊相关的listener
        // EMGroupManager.getInstance().addGroupChangeListener(
        // new MyGroupChangeListener());
        // 通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了
        EMChat.getInstance().setAppInited();

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isConflict || !isCurrentAccountRemoved) {
            updateUnreadLabel();
            updateUnreadSelf();
            // updateUnreadRecommendLable();
            EMChatManager.getInstance().activityResumed();
        }
        if (isConnect == true) {
            initCallInvited();
            countdownTimer.stop();
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("isConflict", isConflict);
        outState.putBoolean(Constant.ACCOUNT_REMOVED, isCurrentAccountRemoved);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        // 注销广播接收者
        try {
            unregisterReceiver(msgReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(ackMessageReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(cmdMessageReceiver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(MainReciver);
        } catch (Exception e) {
        }
        try {
            unregisterReceiver(borderReceiver);
        } catch (Exception e) {
        }
        currentTabIndex = 0;
        // try {
        // unregisterReceiver(offlineMessageReceiver);
        // } catch (Exception e) {
        // }

        if (conflictBuilder != null) {
            conflictBuilder.create().dismiss();
            conflictBuilder = null;
        }
    }

    private void initView() {

        mHomeFragment = new HomeFragment();
        mChatAllHistoryFragment = new ChatAllHistoryFragment();
        mExploreFragment = new ExploreFragment();
        mSelfFragment = new SelfFragment();
        fragments = new Fragment[]{mHomeFragment, mExploreFragment,
                mChatAllHistoryFragment, mSelfFragment};
        // 添加显示第一个fragment
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
        ft.add(R.id.fragment_container, mHomeFragment)
                .add(R.id.fragment_container, mChatAllHistoryFragment)
                .add(R.id.fragment_container, mExploreFragment)
                .hide(mChatAllHistoryFragment).hide(mExploreFragment)
                .show(mHomeFragment).commitAllowingStateLoss();

        unreadLabel = (TextView) findViewById(R.id.unread_msg_number);
        unread_recommend = (ImageView) findViewById(R.id.unread_recommend);
        unreadCustomazitionLable = (ImageView) findViewById(R.id.unread_order_number);
        rlLoverInvited = (RelativeLayout) findViewById(R.id.rlLoverInvited);
        rlNightWhisper = (RelativeLayout) findViewById(R.id.rlNightWhisper);
        linOk = (LinearLayout) findViewById(R.id.linOk);
        tvClose = (ImageView) findViewById(R.id.tvClose);
        btnKnow = (TextView) findViewById(R.id.btnKnow);
        btnKnow.setOnClickListener(this);
        countdownTimer = (coutdownView) findViewById(R.id.countdownTimerLoveCall);
        btnOk = (TextView) findViewById(R.id.btnOk);
        imgCall = (TextView) findViewById(R.id.imgCall);
        tv_tips = (TextView) findViewById(R.id.tv_tips);
        mTabs = new Button[4];
        mTabs[0] = (Button) findViewById(R.id.btnHome);
        mTabs[1] = (Button) findViewById(R.id.btnConversation);
        mTabs[2] = (Button) findViewById(R.id.btnFriend);
        mTabs[3] = (Button) findViewById(R.id.btnSelf);
        mTabs[0].setOnTouchListener(this);
        // 把第一个tab设为选中状态
        mTabs[0].setSelected(true);
        // 导航header
        rvHeader = (HeaderLayout) findViewById(R.id.mainHeader);
        rvHeader.init(HeaderStyle.TEXT_TITLE_IMG);
        rvHeader.InitcursorView();
        rvHeader.setTvNewOnline("空闲恋人 ");
        rvHeader.setTvRecomend(" 梦想恋人");
        rvHeader.setLeftContainerClickListener(new onLeftContainerListener() { // 测试入口

            @Override
            public void onClick() {
                Intent intent = new Intent(Main.this, Test.class);
                Main.this.startActivity(intent);

            }
        });
        rvHeader.setLeftText("test");
        rvHeader.setLeftContentShow(View.GONE);// 隐藏测试入口
        mMediaPlayer = new MediaPlayer(); // 初始化声线
        mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                if (MediaTimer != null) {
                    MediaTimer.cancel();
                }
            }
        });
    }

    /**
     * button点击事件
     *
     * @param view
     */
    public void onTabClicked(View view) {
        if (view.getId() != R.id.btnHome) {
        }
        switch (view.getId()) {
            case R.id.btnHome:
                index = 0;
                rvHeader.init(HeaderStyle.TEXT_TITLE_IMG);
                rvHeader.InitcursorView();
                rvHeader.setTvNewOnline("空闲恋人 ");
                rvHeader.setTvRecomend(" 梦想恋人");
                if (HomeFragment.currIndex == 0) {
                    if (choosedSex == 0) {
                        rvHeader.setRightImg(R.drawable.icon_sex_all);
                    } else if (choosedSex == 1) {
                        rvHeader.setRightImg(R.drawable.icon_sex_man);
                    } else if (choosedSex == 2) {
                        rvHeader.setRightImg(R.drawable.icon_sex_female);
                    }
                    // rvHeader.setRightImg(R.drawable.screen_normal);
                    rvHeader.setRightContentShow(View.VISIBLE);
                } else if (HomeFragment.currIndex == 1) {
                    rvHeader.setRightImg(R.drawable.icon_love_call);
                    rvHeader.setRightContentShow(View.GONE);
                }
                HomeFragment.setHeaderFunction();
                break;
            case R.id.btnConversation:
                index = 1;
                rvHeader.init(HeaderStyle.IMG_TITLE_IMG);
                rvHeader.setMiddleText("发现");
                rvHeader.setLeftContentShow(View.GONE);
                rvHeader.setRightContentShow(View.GONE);

                FriendFragment.setHeaderFunction();
                break;
            case R.id.btnFriend:
                index = 2;
                rvHeader.init(HeaderStyle.TEXT_TITLE_TEXT);
                rvHeader.setRightText("恋人");
                rvHeader.setMiddleText("消息");
                rvHeader.setRightContentShow(View.VISIBLE);
                ChatAllHistoryFragment.setHeaderFunction();
                break;
            case R.id.btnSelf:
                index = 3;
                rvHeader.init(HeaderStyle.TEXT_TITLE_TEXT);
                rvHeader.setRightText("更多");
                rvHeader.setMiddleText("我的");
                rvHeader.setRightContentShow(View.VISIBLE);
                SelfFragment.setHeaderFunction();
                break;
        }
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager()
                    .beginTransaction();
            if (index == 1 && msgFragmentisShow == false) {
                trx.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                msgFragmentisShow = true;
            }
            if (index == 2 && friendFragmentisShow == false) {
                trx.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                friendFragmentisShow = true;
            }
            if (index == 3 && selfFragmentisShow == false) {
                trx.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
                selfFragmentisShow = true;
            }
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commitAllowingStateLoss();
        }
        mTabs[currentTabIndex].setSelected(false);
        // 把当前tab设为选中状态
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    private void initComponents() {
        // 检查新版本
        myUpdateService = new UpdateService(Main.this, true);
        myUpdateService.update();
        UpdateConfig.setUpdateAutoPopup(false);

        // 社会化分享
        myShareSevice = new shareService(this);

        // 高德定位
        startLocation();
    }

    private void startLocation() {
        mLocationManager = TencentLocationManager.getInstance(Main.this);
        // 创建定位请求
        TencentLocationRequest request = TencentLocationRequest
                .create()
                .setRequestLevel(
                        TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA)
                .setInterval(mInterval); // 设置定位周期, 建议值为 1s-20s

        // 开始定位
        // mLocationManager.requestLocationUpdates(request, Main.this);
    }

    @Override
    public void onLocationChanged(TencentLocation location, int error,
                                  String reason) {
        String msg = null;
        if (error == TencentLocation.ERROR_OK) {
            // 定位成功
            Main.mLatitude = location.getLatitude();
            Main.mLontitude = location.getLongitude();
            String city = location.getCity();
            Main.locatedCity = city.substring(0, city.length() - 1);
            // Log.e("===city", Main.locatedCity);
            TencentLocationManager locationManager = TencentLocationManager
                    .getInstance(Main.this);
            locationManager.removeUpdates(Main.this);
        } else {
            // 定位失败
            msg = "定位失败: " + reason;
            // ToolKits.toast(Main.this, msg);
        }
    }

    @Override
    public void onStatusUpdate(String arg0, int arg1, String arg2) {
        // ignore
    }

    /**
     * 重写onKeyDown方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            showExitAlet();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showExitAlet() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            Toast toast = Toast.makeText(Main.this, "再按一次退出程序",
                    Toast.LENGTH_LONG);
            // 可以控制toast显示的位置
            toast.setGravity(Gravity.BOTTOM, 0, 150);
            toast.show();
            mExitTime = System.currentTimeMillis();

        } else {
            Main.this.finish();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        for (MyOnTouchListener listener : touchListeners) {
            listener.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }

    private ArrayList<MyOnTouchListener> touchListeners = new ArrayList<MyOnTouchListener>();

    public void registerListener(MyOnTouchListener listener) {
        touchListeners.add(listener);
    }

    public void unRegisterListener(MyOnTouchListener listener) {
        touchListeners.remove(listener);
    }

    public HeaderLayout getHeader() {
        return rvHeader;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Fragment selfFragment = fragments[currentTabIndex];
        selfFragment.onActivityResult(requestCode, resultCode, data);

    }

	/*
     * 聊天相关
	 */

    /**
     * 刷新未读消息数
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            unreadLabel.setText(String.valueOf(count));
            unreadLabel.setVisibility(View.VISIBLE);
        } else {
            unreadLabel.setVisibility(View.INVISIBLE);
        }
    }

    public void updateUnreadSelf() {
        runOnUiThread(new Runnable() {
            public void run() {
                int count = getUnreadCustomazitonCountTotal()
                        + getUnreadLikerCountTotal();
                // Log.e("getUnreadAddressCountTotal", count + "");
                if (count > 0) {
                    unreadCustomazitionLable.setVisibility(View.VISIBLE);
                } else {
                    unreadCustomazitionLable.setVisibility(View.INVISIBLE);
                }
            }
        });

    }

    // /**
    // * 刷新编辑推荐消息数
    // */
    // public void updateUnreadRecommendLable() {
    // runOnUiThread(new Runnable() {
    // public void run() {
    // int count = getUnreadRecommendCountTotal();
    // Log.e("getUnreadRecommendCountTotal", count + "");
    // if (count > 0) {
    // unread_recommend.setVisibility(View.VISIBLE);
    // } else {
    // unread_recommend.setVisibility(View.INVISIBLE);
    // }
    // }
    // });
    //
    // }

    /**
     * 获取未读申请与通知消息
     *
     * @return
     */
    public int getUnreadInviteCountTotal() {
        int unreadAddressCountTotal = 0;
        ShareReferanceUtils unreadInviteCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadInvite_"
                + UserService.getCurrentUserId());
        unreadAddressCountTotal = unreadInviteCount.getIntValue("count", 0);
        return unreadAddressCountTotal;
    }

    /**
     * 获取未读定制通知消息
     *
     * @return
     */
    public int getUnreadCustomazitonCountTotal() {
        int unreadCustomazitionCountTotal = 0;
        ShareReferanceUtils unreadCustomatizonCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadCustomaziton_"
                + UserService.getCurrentUserId());
        unreadCustomazitionCountTotal = unreadCustomatizonCount.getIntValue(
                "count", 0);
        return unreadCustomazitionCountTotal;
    }

    /**
     * 获取未读申请与通知消息
     *
     * @return
     */
    public int getUnreadRecommendCountTotal() {
        int unreadRecommendCountTotal = 0;
        ShareReferanceUtils unreadRecommendCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadRecommend_"
                + UserService.getCurrentUserId());
        unreadRecommendCountTotal = unreadRecommendCount
                .getIntValue("count", 0);
        return unreadRecommendCountTotal;
    }

    /**
     * 获取未读被喜欢消息
     *
     * @return
     */
    public int getUnreadLikerCountTotal() {
        int unreadAddressCountTotal = 0;
        ShareReferanceUtils unreadLikerCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadLiker_"
                + UserService.getCurrentUserId());
        unreadAddressCountTotal = unreadLikerCount.getIntValue("count", 0);
        return unreadAddressCountTotal;
    }

    /**
     * 获取未读消息数
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
        return unreadMsgCountTotal;
    }

    public static void clearRecommendRecord() {
        ShareReferanceUtils unreadRecommendCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadRecommend_"
                + UserService.getCurrentUserId());
        unreadRecommendCount.setIntValue("count", 0);
        Main.refreshRecommend(); // 刷新红点
    }

    /**
     * 新消息广播接收者
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 主页面收到消息后，主要为了提示未读，实际消息内容需要到chat页面查看

            String from = intent.getStringExtra("from");
            // 消息id
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = EMChatManager.getInstance().getMessage(msgId);

            // fix: logout crash， 如果正在接收大量消息
            // 因为此时已经logout，消息队列已经被清空， broadcast延时收到，所以会出现message为空的情况
            if (message == null) {
                return;
            }

            // 2014-10-22 修复在某些机器上，在聊天页面对方发消息过来时不立即显示内容的bug
            if (ChatActivity.activityInstance != null) {
                if (message.getChatType() == ChatType.GroupChat) {
                    if (message.getTo().equals(
                            ChatActivity.activityInstance.getToChatUsername()))
                        return;
                } else {
                    if (from.equals(ChatActivity.activityInstance
                            .getToChatUsername()))
                        return;
                }
            }

            // 处理不同的消息
            String type = message.getStringAttribute("type", "");
            // 当消息为新的 应聘者
            // Log.e("isNew", type);
            // if (type.equals(C.EMMESSAGE_EXT_TYPE_FRIEND_APPLY))
            // MolianContactManager.getInstance().onContactInvited();
            // if (type.equals(C.EMMESSAGE_EXT_TYPE_FRIEND_APPLY_ACCEPTED))
            // MolianContactManager.getInstance().onContactAgreed();

            // 注销广播接收者，否则在ChatActivity中会收到这个广播
            abortBroadcast();

            notifyNewMessage(message);

            // 刷新bottom bar消息未读数
            updateUnreadLabel();
            if (currentTabIndex == 2) {
                // 当前页面如果为聊天历史页面，刷新此页面
                if (mChatAllHistoryFragment != null) {
                    mChatAllHistoryFragment.refresh();
                }
            }

        }
    }

    /**
     * 消息回执BroadcastReceiver
     */
    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();

            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");

            EMConversation conversation = EMChatManager.getInstance()
                    .getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);

                if (msg != null) {

                    // 2014-11-5 修复在某些机器上，在聊天页面对方发送已读回执时不立即显示已读的bug
                    if (ChatActivity.activityInstance != null) {
                        if (msg.getChatType() == ChatType.Chat) {
                            if (from.equals(ChatActivity.activityInstance
                                    .getToChatUsername()))
                                return;
                        }
                    }

                    msg.isAcked = true;
                }
            }

        }
    };

    /**
     * 透传消息BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            EMLog.d(TAG, "收到透传消息");
            // 获取cmd message对象
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            // 获取消息body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String action = cmdMsgBody.action;// 获取自定义action

            // 获取扩展属性 此处省略

            String userId = message.getStringAttribute("from", "");
            EMLog.e(TAG,
                    String.format("透传消息：action:%s,message:%s", action,
                            message.toString()));
            // Log.e("action", action);
            if (action.equals(C.ACTION_FRIEND_APPLY))
                MolianContactManager.getInstance().onContactInvited(message);
            if (action.equals(C.ACTION_FRIEND_APPLY_ACCEPTED))
                MolianContactManager.getInstance().onContactAgreed(userId);
            if (action.equals(C.ACTION_FRIEND_DELETE))
                MolianContactManager.getInstance().onContactDeleted(userId);
            if (action.equals(C.ACTION_CHAT_APPLY_ACCEPT))
                MolianContactManager.getInstance().onChatApplyAgree(userId);
            if (action.equals(C.ACTION_NEW_LIKER))
                MolianContactManager.getInstance().onNewLike(message);
            if (action.equals(C.ACTION_UPDATE_PROFILE))
                MolianContactManager.getInstance().onUpdate(message.getFrom());
            if (action.equals(C.ACTION_RECOMMENT))
                MolianContactManager.getInstance().onNewRecommend();
            if (action.equals(C.ACTION_AUTHENTICATE_SUCCEED)
                    || action.equals(C.ACTION_AUTHENTICATE_FAILD)) {
                refreshUserInBackground();
            }
            if (action.equals(C.ACTION_RESET_USER)) {
                refreshUserInBackground();
            }
            if (action.equals(C.ACTION_DISABLE_CHAT)) {
                MolianContactManager.getInstance().onChatConversationDelete(
                        message.getFrom());
            }
            if (action.equals(C.ACTION_DISABLE_USER)) {// 封号
                MolianContactManager.getInstance().onDisableUser(userId);
            }
            if (action.equals(C.ACTION_FORBIDDEN_USER)) {// 禁言
                MolianContactManager.getInstance().onForbiddenUser(userId);
            }
            if (action.equals(C.ACTION_CALL_LIKE)) {
                MolianContactManager.getInstance().onCallLiked(
                        message.getFrom());
            }
            if (action.equals(C.ACTION_CUSTOMAZITION_CALL)) {
                MolianContactManager.getInstance().onCustomazitionCall(
                        message.getFrom());
            }
            // 收到定制的订单
            if (action.equals(C.ACTION_NEW_CUSTOMIZATION)) {
                MolianContactManager.getInstance().onNewCustomazition();
            }
            // 自己的测试单被恋爱体验师回复
            if (action.equals(C.ACTION_TESTORDER_LOVER_REPLAY)) {
                MolianContactManager.getInstance()
                        .onTestOrderBeReplyed(message);
            }

            // 正式单中普通人续时，告知时间增加
            if (action.equals(C.ACTION_ORDER_NORMAL_ADDTIME)
                    || action.equals(C.ACTION_ORDER_NORMAL_START)) {
                String time = message.getStringAttribute("time", "");
                MolianContactManager.getInstance().onNewOrderBeCreated(message);
            }

            // 收到恋爱体验师回复的新的单
            if (action.equals(C.ACTION_ORDER_LOVER_REPLAY)) {
                MolianContactManager.getInstance().onNewOrderBeReplyed(message);
            }

            // 收到恋爱体验师的爱心加时
            if (action.equals(C.ACTION_ORDER_LOVER_ADDTIME)) {
                MolianContactManager.getInstance().onTimeAddedByLover(message);
            }

            // 测试单收到时间结束的投产
            if (action.equals(C.ACTION_TESTORDER_LOVER_FINISH)) {
                MolianContactManager.getInstance().onTestOrderFinish(message);
            }

            // 正式单收到时间结束的投产
            if (action.equals(C.ACTION_ORDER_LOVER_FINISH)) {
                MolianContactManager.getInstance().onOrderFinish(message);
            }

        }
    };

    private void refreshUserInBackground() {
        UserService.getCurrentUser().refreshInBackground(
                new RefreshCallback<AVObject>() {

                    @Override
                    public void done(AVObject arg0, AVException arg1) {
                        if (arg1 == null) {
                            MLCache.getCache()
                                    .put(UserService.getCurrentUserId(),
                                            UserService.getCurrentUser()
                                                    .toJSONObject());
                            reInitChannel(); // 退订之后需要重新保存 Installation

                        } else {
                            ToolKits.toast(Main.this, "网络错误");
                        }
                    }
                });
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("touserIds", MLCache.getAllChatId());
        params.put("fromuserId", UserService.getCurrentUserId());
        AVCloud.callFunctionInBackground("sendUpdateMsg", params, null);
    }

    private void reInitChannel() {
        if (UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.subscribe(Main.this, "SweetMale", Main.class);
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.subscribe(Main.this, "SweetFemale", Main.class);
            }
        } else if (UserService.getCurrentUser().getType() == C.USER_TYPE_NORMAL) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.unsubscribe(Main.this, "SweetMale");
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.unsubscribe(Main.this, "SweetFemale");
            }
        }

    }

    private void cancleChannel() {
        PushService.unsubscribe(Main.this, UserService.getCurrentUserId());
        if (UserService.getCurrentUser().getType() == C.USER_TYPE_LOVER
                || UserService.getCurrentUser().getType() == C.USER_TYPE_RECOMMENDED) {
            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_MALE) {
                PushService.unsubscribe(Main.this, "SweetMale");
            } else if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE) {
                PushService.unsubscribe(Main.this, "SweetFemale");
            }
        }

    }

    /***
     * 好友变化listener
     */
    private class MyContactListener implements MolianContactListerner {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // 保存增加的联系人

        }

        @Override
        public void onContactDeleted(final String userId) {
            // 将好友移动到陌生人
            MLCache.deletFriend(userId);
            UserService.removeFollowUser(userId);
            runOnUiThread(new Runnable() {
                public void run() {

                    // 删除与此人的会话
                    EMChatManager.getInstance().deleteConversation(userId);
                    // 如果是在聊天页面删除的好友,怎关闭页面
                    if (ChatActivity.activityInstance != null) {
                        if (userId.equals(ChatActivity.activityInstance
                                .getToChatUsername())) {
                            ChatActivity.activityInstance.finish();
                        }
                    }

                    updateUnreadLabel();
                    // 刷新ui
                    if (currentTabIndex == 2)
                        mChatAllHistoryFragment.refresh();
                }
            });

        }

        @Override
        public void onContactInvited(EMMessage message) {
            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            notifyNewIviteMessage(message);

        }

        @Override
        public void onContactAgreed(String userId) {
            // 保存好友id
            MLCache.saveFriendId(userId);
            // 如果是在聊天页面则刷新头部和可以打电话
            if (ChatActivity.activityInstance != null) {
                if (userId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    ChatActivity.activityInstance.freshFriendStatus();
                }
            }

        }

        @Override
        public void onContactRefused(String username) {
            // 参考同意，被邀请实现此功能,demo未实现
            // Log.d(username, username + "拒绝了你的好友请求");
        }

        @Override
        public void onChatApplyAgree(final String userId) {
            // Log.e("会话申请", "被同意");
            // runOnUiThread(new Runnable() {
            // public void run() {
            // // 如果正在与此用户的聊天页面
            // String st10 = getResources().getString(
            // R.string.have_you_removed);
            // if (UserProfile.userProfileInstance != null) {
            // if (userId.equals(UserProfile.userProfileInstance
            // .getCurUserId())) {
            // // Log.e("会话申请", "刷新");
            // UserProfile.userProfileInstance
            // .refreshApplyStatus();
            // }
            // }
            // }
            // });

        }

        @Override
        public void onNewLike(EMMessage message) {
            // Log.e("tip", "我被喜欢啦啦啦啦啦啦");
            notifyNewLikerMessage(message);
            if (currentTabIndex == 3) {
                mSelfFragment.refresh();// 恋爱呼叫
            }

        }

        @Override
        public void onNewRecommend() {
            // Log.e("tip", "有新的编辑推荐");
            notifyNewRecommendrMessage();
        }

        @Override
        public void onChatConversationDelete(String userId) {
        }

        @Override
        public void onForbiddenUser(String userId) {
            UserService.getCurrentUser().refreshInBackground(null);
            SimpleDateFormat sDateFormat = new SimpleDateFormat(
                    "yyyy-MM-dd hh:mm:ss");
            String date = sDateFormat.format(new java.util.Date());
            MLContext.saveForbiddenTime("forbidden", date);
        }

        @Override
        public void onDisableUser(String userId) {
            cancleChannel(); // 退订之后需要重新保存 Installation
            AVInstallation.getCurrentInstallation().saveInBackground();
            final ProgressDialog pd = new ProgressDialog(Main.this);
            String st = getResources().getString(R.string.Are_logged_out);
            pd.setMessage(st);
            pd.setCanceledOnTouchOutside(false);
            pd.show();
            MLApplication.getInstance().logout(new EMCallBack() {

                @Override
                public void onSuccess() {
                    Main.this.runOnUiThread(new Runnable() {
                        public void run() {
                            // 重新显示登陆页面
                            MLUser.logOut();
                            MLContext.deleteAll(); // 删除所有sharepreference
                            pd.dismiss();

                            Intent intent2 = new Intent(Main.this,
                                    TempMain.class);
                            intent2.putExtra("status",
                                    String.valueOf(C.USER_STATUS_DISABLE));
                            Main.this.startActivity(intent2);
                            Main.this.finish();
                            Main.getInstance().finish();
                        }
                    });
                }

                @Override
                public void onProgress(int progress, String status) {

                }

                @Override
                public void onError(int code, String message) {

                }
            });
        }

        @Override
        public void onCallLiked(String userId) {
            if (RandomCallActivity.randomCallInstance != null) {
                if (userId.equals(RandomCallActivity.randomCallInstance
                        .getToUserId())) {
                    RandomCallActivity.randomCallInstance.isBeLiked = true;
                    RandomCallActivity.randomCallInstance.refeshHeader(1);
                }
            }

        }

        @Override
        public void onCustomazitionCall(String userId) {
            // 当定制的电话打过来的时候
            customazitonLoverId = userId;
        }

        @Override
        public void onNewCustomazition() {
            // 有新的定制需求
            saveNewCustomazitonMsg();
            // 提示有新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
            // 刷新bottom bar消息未读数
            updateUnreadSelf();
            // 刷新好友页面ui
            if (currentTabIndex == 3) {
                mSelfFragment.refresh();// 恋爱呼叫
            }
        }

        @Override
        public void onTestOrderBeReplyed(EMMessage message) {
            // 当试聊单被回复的时候
            // 给本地添加一个新的消息提示用户
            String replyUserId = null;
            String nickname = message.getStringAttribute("nickname", "");
            replyUserId = message.getFrom();
            MolianContactManager.getInstance().saveNewGrayMsg(replyUserId,
                    nickname, C.GRAY_MEG_NORMAL_REPPLIED, "");

            // 初始化外部定时器
            String orderId = message.getStringAttribute("orderId", "");
            MLOrderTimer.getInstance().initTimerByTestOrder(orderId);

            // 如果在和这个人聊天
            if (ChatActivity.activityInstance != null) {
                if (replyUserId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    // 刷新页面
                    ChatActivity.activityInstance.freshMsg();
                    // 初始化定时器
                    ChatActivity.activityInstance.initTimer(
                            ChatActivity.activityInstance.testOrderTime, true);

                } else {

                }
            }

        }

        @Override
        public void onNewOrderBeCreated(EMMessage message) {
            // 现判断是不是好友
            String userId = null;
            userId = message.getFrom();
            if (!MLCache.isFriend(userId)) {
                UserService.getCurrentUser().followInBackground(userId, null);
            }

            String nickname = message.getStringAttribute("nickname", "");
            String time = message.getStringAttribute("time", "");
            // MolianContactManager.getInstance().saveNewGrayMsg(userId,
            // nickname,
            // C.GRAY_MEG_NORMAL_REPPLIED, "");
            MolianContactManager.getInstance().saveNewGrayMsg(userId, nickname,
                    C.GRAY_MEG_LOVER_TIMEADDED, time);

            // notifyNewMessage(message);

            // 刷新bottom bar消息未读数
            updateUnreadLabel();
            if (currentTabIndex == 2) {
                // 当前页面如果为聊天历史页面，刷新此页面
                if (mChatAllHistoryFragment != null) {
                    mChatAllHistoryFragment.refresh();
                }
            }
            // 如果在和这个人聊天
            if (ChatActivity.activityInstance != null) {
                if (userId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    // 刷新页面
                    ChatActivity.activityInstance.freshMsg();
                    // 初始化定时器
                    boolean isWinnerNewOrder = true;// 有新单
                    ChatActivity.activityInstance
                            .freshOrderAndiniTimer(isWinnerNewOrder);

                }
            }

        }

        @Override
        public void onNewOrderBeReplyed(EMMessage message) {
            // 初始化外部定时器
            String orderId = message.getStringAttribute("orderId", "");
            MLOrderTimer.getInstance().initTimerByOrder(orderId);

            // 新的订单被恋爱体验师回复
            // 如果在和这个人聊天
            String replyUserId = null;
            replyUserId = message.getFrom();
            if (ChatActivity.activityInstance != null) {
                if (replyUserId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    // 初始化定时器
                    boolean isWinnerNewOrder = false;// 被回复
                    ChatActivity.activityInstance
                            .freshOrderAndiniTimer(isWinnerNewOrder);

                }
            }

        }

        @Override
        public void onTimeAddedByLover(EMMessage message) {
            String nickname = message.getStringAttribute("nickname", "");
            String userId = message.getFrom();

            // 保存一条本地提示
            MolianContactManager.getInstance().saveNewGrayMsg(userId, nickname,
                    C.GRAY_MEG_NORMAL_ADDED, null);

            // 刷新bottom bar消息未读数
            updateUnreadLabel();
            if (currentTabIndex == 2) {
                // 当前页面如果为聊天历史页面，刷新此页面
                if (mChatAllHistoryFragment != null) {
                    mChatAllHistoryFragment.refresh();
                }
            }

            // 如果在和这个人聊天
            if (ChatActivity.activityInstance != null) {
                if (userId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    // geng
                    ChatActivity.activityInstance.freshLoverTenAddedTimer();

                }
            }

        }

        @Override
        public void onTestOrderFinish(EMMessage message) {
            String nickname = message.getStringAttribute("nickname", "");
            String userId = message.getFrom();

            MolianContactManager.getInstance().saveNewGrayMsg(userId, nickname,
                    C.GRAY_MEG_TEST_LOVER_TIMEOUT, null);

            // 如果在和这个人聊天
            if (ChatActivity.activityInstance != null) {
                if (userId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    // geng
                    ChatActivity.activityInstance.freshMsg();

                }
            }

        }

        @Override
        public void onOrderFinish(EMMessage message) {
            String nickname = message.getStringAttribute("nickname", "");
            String userId = message.getFrom();

            MolianContactManager.getInstance().saveNewGrayMsg(userId, nickname,
                    C.GRAY_MEG_LOVER_TIMEOUT, null);

            // 如果在和这个人聊天
            if (ChatActivity.activityInstance != null) {
                if (userId.equals(ChatActivity.activityInstance
                        .getToChatUsername())) {
                    // geng
                    ChatActivity.activityInstance.freshMsg();
                }
            }

        }
    }

    /**
     * 保存提示新消息
     *
     * @param message
     * @param msg
     */
    private void notifyNewIviteMessage(EMMessage message) {
        // saveInviteMsg();
        // 提示有新消息
        EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
        notifyThoughMessage(message, NewLover.class, NEW_FRIEND_APPLY, null);

    }

    /**
     * 被喜欢后新消息提示
     */
    private void notifyNewLikerMessage(EMMessage message) {
        saveLikerMsg();
        // 提示有新消息
        // EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
        // notifyThoughMessage(message, NewFollow.class, NEW_LIKE, null);
        // 更新红点
        updateUnreadSelf();

    }

    /**
     * 有新编辑推荐时消息提示
     */
    private void notifyNewRecommendrMessage() {
        saveRecommendMsg();
        // 提示有新消息
        EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
        // 刷新bottom bar消息未读数
        // updateUnreadRecommendLable();
        // 刷新好友页面ui
        if (currentTabIndex == 0)
            refreshRecommend();
    }

    public static void refreshRecommend() {
        // 刷新编辑推荐
        ShareReferanceUtils unreadRecommendCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadRecommend_"
                + UserService.getCurrentUserId());
        int count = unreadRecommendCount.getIntValue("count", 0);
        if (count == 0) {
            HeaderLayout.setRecommendCircleGone();
        } else {
            HeaderLayout.setRecommendCircle();
        }
        // updateUnreadAddressLable();
    }

    /**
     * 保存被喜欢的msg
     *
     * @param msg
     */
    private void saveLikerMsg() {
        ShareReferanceUtils unreadLikerCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadLiker_"
                + UserService.getCurrentUserId());
        int count = unreadLikerCount.getIntValue("count", 0);
        unreadLikerCount.setIntValue("count", count + 1);
    }

    /**
     * 保存新的定制的msg
     *
     * @param msg
     */
    private void saveNewCustomazitonMsg() {
        ShareReferanceUtils unreadCustomazitonCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadCustomaziton_"
                + UserService.getCurrentUserId());
        int count = unreadCustomazitonCount.getIntValue("count", 0);
        unreadCustomazitonCount.setIntValue("count", count + 1);
    }

    /**
     * 保存推荐msg
     *
     * @param msg
     */
    private void saveRecommendMsg() {
        ShareReferanceUtils unreadRecommendCount = new ShareReferanceUtils(
                MLApplication.getContext(), "UnreadRecommend_"
                + UserService.getCurrentUserId());
        int count = unreadRecommendCount.getIntValue("count", 0);
        unreadRecommendCount.setIntValue("count", count + 1);
    }

    /**
     * set head
     *
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance()
                    .get(headerName.substring(0, 1)).get(0).target.substring(0,
                            1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }

    /**
     * 连接监听listener
     */
    private class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mChatAllHistoryFragment.errorItem.setVisibility(View.GONE);
                }

            });
        }

        @Override
        public void onDisconnected(final int error) {
            final String st1 = getResources().getString(
                    R.string.Less_than_chat_server_connection);
            final String st2 = getResources().getString(
                    R.string.the_current_network);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                        showAccountRemovedDialog();
                    } else if (error == EMError.CONNECTION_CONFLICT) {
                        // 显示帐号在其他设备登陆dialog
                        showConflictDialog();
                    } else {
                        mChatAllHistoryFragment.errorItem
                                .setVisibility(View.VISIBLE);
                        if (NetUtils.hasNetwork(Main.this))
                            mChatAllHistoryFragment.errorText.setText(st1);
                        else
                            mChatAllHistoryFragment.errorText.setText(st2);

                    }
                }

            });
        }
    }

    /**
     * 显示帐号在别处登录dialog
     */
    private void showConflictDialog() {
        isConflictDialogShow = true;
        MLApplication.getInstance().logout(null);
        String st = getResources().getString(R.string.Logoff_notification);
        if (!Main.this.isFinishing()) {
            // clear up global variables
            try {
                if (conflictBuilder == null)
                    conflictBuilder = new android.app.AlertDialog.Builder(
                            Main.this);
                conflictBuilder.setTitle(st);
                conflictBuilder.setMessage(R.string.connect_conflict);
                conflictBuilder.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                conflictBuilder = null;
                                finish();
                                startActivity(new Intent(Main.this,
                                        TempMain.class));
                            }
                        });
                conflictBuilder.setCancelable(false);
                conflictBuilder.create().show();
                isConflict = true;
            } catch (Exception e) {
                // EMLog.e(TAG,
                // "---------color conflictBuilder error" + e.getMessage());
            }

        }

    }

    /**
     * 帐号被移除的dialog
     */
    private void showAccountRemovedDialog() {
        isAccountRemovedDialogShow = true;
        MLApplication.getInstance().logout(null);
        String st5 = getResources().getString(R.string.Remove_the_notification);
        if (!Main.this.isFinishing()) {
            // clear up global variables
            try {
                if (accountRemovedBuilder == null)
                    accountRemovedBuilder = new android.app.AlertDialog.Builder(
                            Main.this);
                accountRemovedBuilder.setTitle(st5);
                accountRemovedBuilder.setMessage(R.string.em_user_remove);
                accountRemovedBuilder.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                                accountRemovedBuilder = null;
                                finish();
                                startActivity(new Intent(Main.this,
                                        TempMain.class));
                            }
                        });
                accountRemovedBuilder.setCancelable(false);
                accountRemovedBuilder.create().show();
                isCurrentAccountRemoved = true;
            } catch (Exception e) {
                // Log.e(TAG,
                // "---------color userRemovedBuilder error"
                // + e.getMessage());
            }

        }

    }

    // 判断是否勿扰时段
    public static boolean isNight() {
        int startTime = MLContext.getBorederTimeMessage("message_border_start");
        int endTime = MLContext.getBorederTimeMessage("message_border_end");
        SimpleDateFormat sDateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
        String date = sDateFormat.format(new java.util.Date());
        if (date == null || date.isEmpty()) {
            return false;
        }
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale
                    .getDefault()).parse(date));
            int hour = cal.get(Calendar.HOUR_OF_DAY);
            if (hour >= startTime || hour <= (endTime - 1)) { // 晚上几点到早上几点为夜晚时间
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.linOk:
                isConnect = false;
                linOk.setClickable(false);
                mlCustomizationRecord = new MLCustomizationRecord();
                mlCustomizationRecord.setSponsor(UserService.getCurrentUser());
                mlCustomizationRecord.setStatus(C.LOVE_CALL_WAITING);
                mlCustomizationRecord.setPrice(0.2);
                mlCustomizationRecord.setType(UserService.getCurrentUser()
                        .getGender());
                mlCustomizationRecord.saveInBackground(new SaveCallback() {// 保存一条纪录
                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            // 调用云代码发一条透传给恋爱体验师
                            Map<String, Object> params = new HashMap<String, Object>();

                            if (UserService.getCurrentUser().getGender() == C.USER_GENDER_FEMALE)
                                params.put("type", C.USER_GENDER_MALE);
                            else
                                params.put("type", C.USER_GENDER_FEMALE);

                            AVCloud.callFunctionInBackground(
                                    "sendCustomizationMsg", params, null);

                            AVAnalytics.onEvent(Main.getInstance(),
                                    "情感热线发单成功");
                            imgCall.setVisibility(View.VISIBLE);
                            btnOk.setTextColor(getResources().getColor(
                                    R.color.main_text_color_pink));
                            linOk.setBackgroundResource(R.drawable.shape_btn_sure_grey);
                            tv_tips.setText(getResources().getString(
                                    R.string.loveCalling_tips));
                            countdownTimer.initTime(countdownTime);
                            countdownTimer.setVisibility(View.VISIBLE);
                            btnOk.setVisibility(View.GONE);
                            // 启动倒计时
                            countdownTimer.start();
                            countdownTimer
                                    .setOnTimeCompleteListener(new OnTimeCompleteListener() {

                                        @Override
                                        public void onTimeComplete() {
                                            if (isConnect == false) {
                                                mlCustomizationRecord
                                                        .deleteInBackground(new DeleteCallback() {

                                                            @Override
                                                            public void done(
                                                                    AVException arg0) {
                                                                initCallInvited();
                                                                AVAnalytics
                                                                        .onEvent(
                                                                                Main.this,
                                                                                "情感热线（作废数）");
                                                            }
                                                        });
                                            }
                                        }
                                    });
                        } else {
                            ToolKits.toast(Main.this, "请检查你的网络");
                            linOk.setClickable(true);
                        }
                    }
                });
                break;
            case R.id.tvClose:
                rlLoverInvited.setVisibility(View.GONE);
                break;
            case R.id.btnKnow:
                rlNightWhisper.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        if (MotionEvent.ACTION_DOWN == event.getAction()) {
            if ((int) System.currentTimeMillis() - firClick > 1000) {
                count = 0;
                firClick = 0;
                secClick = 0;
            }
            count++;
            if (count == 1) {
                firClick = (int) System.currentTimeMillis();
                onTabClicked(mTabs[0]);
            } else if (count == 2) {
                secClick = (int) System.currentTimeMillis();
                if (secClick - firClick < 1000) {
                    // 双击事件
                    if (HomeFragment.currIndex == 0) {
                        NewOnlineFragment.dropDownListView.setSelection(0);
                    } else if (HomeFragment.currIndex == 1) {
                        RecommendFragment.articleListview.setSelection(0);
                    }
                } else {
                    onTabClicked(mTabs[0]);
                }
                count = 0;
                firClick = 0;
                secClick = 0;
            }
        }
        return true;
    }
}
